package com.gitee.cui.redis.springjedis;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用RedisTemplate封装类CacheOperationService完成业务处理
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/7 21:39
 **/
@Slf4j
public class UserServiceImplWithTemplate implements UserService {

    private CacheOperationService cacheOperationService;

    public void setCacheOperationService(CacheOperationService cacheOperationService) {
        this.cacheOperationService = cacheOperationService;
    }

    private static final String USER_UID_PREFIX = "user:uid";

    /**
     * 缓存时间，4分钟
     */
    private static final long CACHED_TIME = 60 * 4;

    @Override
    public User saveUser(User user) {
        String key = USER_UID_PREFIX + user.getUid();
        log.info("user: {}", user);
        // 保存到缓存中
        boolean success = cacheOperationService.set(key, user, CACHED_TIME);
        // 保存到数据库中，如MySQL
        return user;
    }

    @Override
    public User getUser(long id) {
        String key = USER_UID_PREFIX + id;
        User user = (User) cacheOperationService.get(key);
        if (user == null) {
            // 从数据库中查询并保存到缓存中

        }
        return user;
    }

    @Override
    public void deleteUser(long id) {
        String key = USER_UID_PREFIX + id;
        // 从缓存中删除
        cacheOperationService.del(key);

        // 从数据库中删除
        log.info("delete user: {}", id);
    }

    @Override
    public void deleteAll() {

    }
}
